#include "Stdafx.h"
#include "HttpRequest.h"

#include "StreamWrappers.h"

#include "poco/URI.h"
#include "poco/Net/HTTPServerRequest.h"

namespace MiniHttpServer
{
	HttpRequest::HttpRequest( Poco::Net::HTTPServerRequest& request ) : m_request(request)
	{
		// Note: this is a hack, as System.Uri cannot handle relative uris well, unfortunately Poco
		// delivers only the path of the uri, not the host, port and scheme, why is that so?
		m_rawuri = gcnew System::String(m_request.getURI().c_str());
		Poco::Net::SocketAddress socketAdress = m_request.serverAddress();
		Poco::URI uri(m_request.getURI());
		uri.setScheme("http");
		uri.setHost(socketAdress.host().toString());
		uri.setPort(socketAdress.port());
		m_uri = gcnew System::Uri(gcnew System::String(uri.toString().c_str()), System::UriKind::Absolute);
		m_method = gcnew System::String(m_request.getMethod().c_str());
		m_contentType = gcnew System::String(m_request.getContentType().c_str());
		m_contentLength = m_request.getContentLength();
		if (m_contentLength == Poco::Net::HTTPMessage::UNKNOWN_CONTENT_LENGTH)
			m_contentLength = 0;	// set to zero for now, we'll have to see if that is okay
		m_userAgent = gcnew System::String(m_request.has("User-Agent") ? m_request.get("User-Agent").c_str() : "");
		m_keepAlive = m_request.getKeepAlive();
		m_requestStream = gcnew InputStreamWrapper(m_request.stream());

		m_headers = gcnew System::Collections::Specialized::NameValueCollection();
		for (auto iter = m_request.begin(); iter != m_request.end(); iter++)
		{
			m_headers->Add(gcnew System::String(iter->first.c_str()), gcnew System::String(iter->second.c_str()));
		};

	}

	HttpRequest::~HttpRequest()
	{
		this->!HttpRequest();
	}

	HttpRequest::!HttpRequest()
	{

	}

	bool HttpRequest::GetHasBody()
	{
		return (ContentLength > 0) && (ContentLength != Poco::Net::HTTPMessage::UNKNOWN_CONTENT_LENGTH);
	}

};